#!/bin/bash

# --- 机器人仓库的绝对路径 ---
# !!! 重要: 确保这个路径是你 PC 上的正确路径
REPO_PATH="/home/xqw/alphadog_ros_ctl"
# -----------------------------------

# 设置ROS 1和ROS 2工作空间的路径
ROS1_WS_PATH="${REPO_PATH}/ros1_ws/dog_msgs_ws"
ROS2_WS_PATH="${REPO_PATH}/ros2_ws"

# 定义会话名称
SESSION_NAME="so101_sim"

# 检查tmux是否已安装
if ! command -v tmux &> /dev/null
then
    echo "错误: tmux 未安装。请先运行 'sudo apt install tmux'"
    exit 1
fi

# 检查会话是否已存在，如果存在则先杀死它
tmux has-session -t $SESSION_NAME 2>/dev/null
if [ $? = 0 ]; then
    echo "检测到已存在的会话，正在关闭..."
    tmux kill-session -t $SESSION_NAME
fi

echo "正在启动新的 tmux 会话: $SESSION_NAME (左右分屏)"

# -----------------------------------------------------------------
# 窗格 0 (左侧): 终端 A (所有 ROS 2 仿真节点)
# -----------------------------------------------------------------
tmux new-session -d -s $SESSION_NAME -n "Simulation" -c $REPO_PATH
tmux send-keys -t $SESSION_NAME:0.0 "source ${ROS2_WS_PATH}/install/setup.bash" C-m
tmux send-keys -t $SESSION_NAME:0.0 "echo '启动所有 ROS 2 仿真节点 (Gazebo, MoveIt, 控制器)...'" C-m
tmux send-keys -t $SESSION_NAME:0.0 "ros2 launch joystick_alphadog_with_so101_servo start_real_dog_with_sim_arm.launch.py" C-m

# -----------------------------------------------------------------
# 窗格 1 (右侧): 终端 B (ROS 1 网桥)
# -----------------------------------------------------------------
tmux split-window -h -t $SESSION_NAME:0.0 -c $REPO_PATH
tmux send-keys -t $SESSION_NAME:0.1 "echo '启动 ROS 1 网桥... (等待 Gazebo 启动)'" C-m
# 为 Gazebo 启动预留更长时间
tmux send-keys -t $SESSION_NAME:0.1 "sleep 10" C-m
# 设置混合环境
tmux send-keys -t $SESSION_NAME:0.1 "source ${ROS1_WS_PATH}/devel/setup.bash" C-m
tmux send-keys -t $SESSION_NAME:0.1 "source ${ROS2_WS_PATH}/install/setup.bash" C-m
tmux send-keys -t $SESSION_NAME:0.1 "ros2 run ros1_bridge dynamic_bridge --bridge-all-topics" C-m

# -----------------------------------------------------------------
# 聚焦到左侧窗格
# -----------------------------------------------------------------
tmux select-pane -t $SESSION_NAME:0.0

echo "所有节点已在 tmux 会话 '$SESSION_NAME' 中启动。"
echo "请运行 'tmux attach -t $SESSION_NAME' 来查看。"